package org.learn.event;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class BallMove extends JFrame{//窗口
    MyPanel mp = null;
    public static void main(String[] args) {
        BallMove ballMove = new BallMove();
    }
    //构造器
    public BallMove(){
        mp = new MyPanel();
        this.add(mp);
        this.setSize(400,300);
        //窗口可以监听键盘事件
        this.addKeyListener(mp);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }
}
//面板，画出小球
//KeyListener监听器，可以监听键盘事件；
class MyPanel extends JPanel implements KeyListener {
    //
    int x = 10;
    int y = 10;
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.fillOval(x,y,20,20);
    }
    //有字符输出时被该方法触发
    @Override
    public void keyTyped(KeyEvent e) {

    }
    //当某个键按下，该方法被触发
    @Override
    public void keyPressed(KeyEvent e) {
      //根据用户按下的不同建，来处理小球的移动；
        if(e.getKeyCode() == KeyEvent.VK_DOWN){
            y++;
        }else if(e.getKeyCode() == KeyEvent.VK_UP){
            y--;
        }else if(e.getKeyCode() == KeyEvent.VK_LEFT){
            x--;
        }else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
            x++;
        }
        //重绘
        this.repaint();
    }
    //当某个键按下释放（松开）该方法会触发
    @Override
    public void keyReleased(KeyEvent e) {

    }
}